import logging
import os
import random
import urllib

from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google_storage import StorageClient

import models


class BaseHandler(webapp.RequestHandler):
   """ BaseHandler that everything should inherit from """
   
   def render(self, filename, context={}):
      path = os.path.join(os.path.dirname(__file__), 'templates', filename)
      self.response.out.write(template.render(path, context))
      

class MainPage(BaseHandler):
   """ Renders the main page """
   
   def get(self):
      self.render("index.html", {})


class SearchPage(BaseHandler):
  """The live search page. """

  def get(self, model_id, query):
    model = models.PredictionModel(
        name='Test model',
        owner=users.get_current_user(),
        public=True,
        categories=['Negative', 'Neutral', 'Positive'],
    )
    self.render("search.html", {
        'model_id': model_id,
        'query': urllib.unquote(query),
        'model': model,
    })


class ClassifyPage(BaseHandler):
  def post(self, model_id):
    tweets = simplejson.loads(self.request.body)
    for tweet in tweets:
      tweet['category'] = random.randrange(3)
    self.response.headers['Content-Type'] = 'application/json'
    self.response.out.write(simplejson.dumps(tweets))

class TestStorage(BaseHandler):
    """ Renders the storage test page """

    def get(self):
        storage = StorageClient()
        storage.create_object('test1', 'content')

ROUTES = [
   ('/', MainPage),
   ('/search/(\d+)/(.*)', SearchPage),
   ('/classify/(\d+)', ClassifyPage),
   ('/test_storage', TestStorage)
]

application = webapp.WSGIApplication(ROUTES, debug=True)

def main():
    util.run_wsgi_app(application)

if __name__ == "__main__":
    main()